﻿using SYMetro.Domain.Modal.Membership;
using SYMetro.Repository.EntityFramework.ModelConfigurations.Membership;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YiDa.Domain;

namespace SYMetro.Repository.EntityFramework
{
    public class SYMetroDbContext : DbContext
    {
        public DbSet<Role> Roles { get; set; }
        public DbSet<User> Users { get; set; }


        public SYMetroDbContext()
            : base("SYMetroDbContext")
        {
            this.Configuration.AutoDetectChangesEnabled = true;
            this.Configuration.LazyLoadingEnabled = true;
            this.Configuration.ValidateOnSaveEnabled = true;

        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations
                .Add(new RoleTypeConfiguration())
                .Add(new UserTypeConfiguration());

            base.OnModelCreating(modelBuilder);
        }

        protected override bool ShouldValidateEntity(System.Data.Entity.Infrastructure.DbEntityEntry entityEntry)
        {
            return base.ShouldValidateEntity(entityEntry);
        }

        protected override DbEntityValidationResult ValidateEntity(System.Data.Entity.Infrastructure.DbEntityEntry entityEntry, IDictionary<object, object> items)
        {
            var result = new DbEntityValidationResult(entityEntry, new List<DbValidationError>());

            if ((entityEntry.State == EntityState.Added || entityEntry.State == System.Data.EntityState.Modified) && entityEntry.Entity is IEntity)
            {
                if (((IEntity)entityEntry.Entity).ID == Guid.Empty)
                {
                    result.ValidationErrors.Add(new DbValidationError("ID", "在新增或修改实体时,ID属性必需赋值."));
                }
            }
            if (!result.IsValid)
            {
                return result;
            }
            return base.ValidateEntity(entityEntry, items);
        }

        public override int SaveChanges()
        {
            return base.SaveChanges();
        }
    }
}
